package com.bw.module_home

import android.content.Intent
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bw.lib_common.base.BaseMVIFragment
import com.bw.lib_common.fps.FpsMonitor
import com.bw.module_cinema.search.SearchActivity
import com.bw.module_home.databinding.FragmentHomeBinding
import com.bw.module_home.intent.HomeSimpleIntent
import com.bw.module_home.model.Adpter.HomeTitleApter
import com.bw.module_home.model.Adpter.HomeVideoApter
import com.bw.module_home.model.entity.RecommendVideoEntityItem
import com.bw.module_home.model.entity.SimpleVideoEntity
import com.bw.module_detail.widget.RedPacketEnum
import com.bw.module_detail.widget.RedPacketEvent
import com.bw.module_detail.widget.RedPacketWidget
import com.bw.module_home.state.HomeSimpleTypeState
import com.bw.module_home.viewModel.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

@AndroidEntryPoint
class HomeFragment : BaseMVIFragment() {
    private val binding: FragmentHomeBinding by lazy{
        FragmentHomeBinding.inflate(layoutInflater)
    }
    
    var mAdapter: HomeTitleApter? = null
    var mAdapter1: HomeVideoApter? = null
    private lateinit var mViewModel: HomeViewModel
    private lateinit var redPacketWidget: RedPacketWidget
    
    override fun onPause() {
        super.onPause()
        // 暂停所有视频播放并释放资源
        mAdapter1?.releaseAllPlayers()
        // 暂停红包动画
        redPacketWidget.pause()
        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.PAUSE))
    }
    
    override fun onResume() {
        super.onResume()
        // 恢复时不需要自动播放，等待用户点击
        // 恢复红包动画
        redPacketWidget.resume()
        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.RESUME))
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 释放所有播放器资源
        mAdapter1?.releaseAllPlayers()
        // 停止红包动画
        redPacketWidget.stop()
        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.STOP))
    }
    
    private var redPacketCompleted = false

    // 分页相关变量
    private var currentPage = 1
    private val pageSize = 20
    private var isLoadingMore = false
    private var hasMoreData = true
    private val videoList = mutableListOf<SimpleVideoEntity>()

    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun getFragmentRootView(): View {
        return binding.root
    }

    override fun initView() {
        super.initView()
        mAdapter = HomeTitleApter()
        binding.rv1.layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false)
        binding.rv1.adapter = mAdapter
        
        // 初始化红包挂件 - 使用详情页面的组件
        redPacketWidget = binding.redPacketWidget
        redPacketWidget.setStateCallBack(object : com.bw.module_detail.widget.RedPacketWidget.StateCallBack {
            override fun completed() {
                // 因为动画会循环，使用标志确保只显示一次提示
                if (!redPacketCompleted) {
                    redPacketCompleted = true
                    showMsg("红包已领取")
                }
            }
        })
        redPacketWidget.setNum(10) // 设置红包金额
        
        // 设置搜索栏点击事件
        binding.topBar.setOnClickListener {
            startActivity(Intent(context, SearchActivity::class.java))
        }

    }

    override fun initData() {
        super.initData()

        // 发送初始化事件，开始红包动画
        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.INIT))
        redPacketWidget.start()
        
        // 初始化RecyclerView布局管理器

        binding.rv2.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

        // 初始化刷新组件
        initRefreshView()

        // 初始化滚动监听
        initScrollListener()

        lifecycleScope.launch {
            mViewModel.intents.send(HomeSimpleIntent.getSimpleVideoByChannelId("94349546935",currentPage,pageSize))
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.intents.send(HomeSimpleIntent.getSimpleType)
                loadData(1, true)
            }
        }

        mAdapter?.setOnTypeItemClickListener(object :HomeTitleApter.OnItemClickListener{
            override fun onItemClick(id: String) {
                lifecycleScope.launch {

                    mViewModel.intents.send(HomeSimpleIntent.getSimpleVideoByChannelId(id.toString(),currentPage,pageSize))
                }
            }

        })
    }

    private fun initRefreshView() {
        // 设置下拉刷新颜色
        binding.swipeRefreshLayout.setColorSchemeResources(
            android.R.color.holo_blue_light,
            android.R.color.holo_red_light,
            android.R.color.holo_green_light
        )

        // 设置下拉刷新监听器
        binding.swipeRefreshLayout.setOnRefreshListener {
            // 重置状态，重新加载第一页
            currentPage = 1
            hasMoreData = true
            // 确保刷新动画正在显示
            binding.swipeRefreshLayout.isRefreshing = true
            loadData(currentPage, true)
        }
    }

    private fun initScrollListener() {
        val layoutManager = binding.rv2.layoutManager as LinearLayoutManager

        binding.rv2.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 只有向下滚动且有更多数据且不在加载中时才处理加载更多
                if (dy > 0 && hasMoreData && !isLoadingMore) {
                    val visibleItemCount = layoutManager.childCount
                    val totalItemCount = layoutManager.itemCount
                    val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

                    // 当滚动到倒数第10个item时，开始加载更多
                    if (visibleItemCount + firstVisibleItemPosition >= totalItemCount - 10) {
                        loadMoreData()
                    }
                }
            }
            
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                
                // 当滚动状态变为停止时检查当前播放的视频是否还在可视区域内
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 获取当前正在播放的视频位置
                    val currentPlayingPos = mAdapter1?.getCurrentPlayingPosition() ?: -1
                    
                    if (currentPlayingPos != -1) {
                        // 检查当前播放的视频是否在可视区域内
                        val firstVisiblePos = layoutManager.findFirstVisibleItemPosition()
                        val lastVisiblePos = layoutManager.findLastVisibleItemPosition()
                        
                        // 如果当前播放的视频不在可视区域内，则停止播放
                        if (currentPlayingPos < firstVisiblePos || currentPlayingPos > lastVisiblePos) {
                            // 使用新添加的stopVideoAtPosition方法来精确停止不在可视区域内的视频播放
                            mAdapter1?.stopVideoAtPosition(currentPlayingPos)
                            // 这样可以只停止不在可视区域内的当前播放视频，而不影响其他视频
                            // 用户可以滚动后点击其他视频继续观看，提供更好的用户体验
                        }
                    }
//                    FpsMonitor.instance.start(1000)
                }
            }
        })
    }


    private fun loadData(page: Int, isRefresh: Boolean) {
        lifecycleScope.launch {
            mViewModel.intents.send(HomeSimpleIntent.getRecommendSimpleVideo(page, pageSize))
        }
    }

    private fun loadMoreData() {
        if (!isLoadingMore && hasMoreData) {
            isLoadingMore = true
            currentPage++
            loadData(currentPage, false)
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                launch {
                    mViewModel.simpleTypeStateFlow_.collect{
                        when(it){
                            is HomeSimpleTypeState.Init -> {}
                            is HomeSimpleTypeState.Loading -> {
                                // 加载状态不做特殊处理，因为下拉刷新和上拉加载有各自的状态管理
                                // 如果需要全局加载动画，可以在这里添加
                            }
                            is HomeSimpleTypeState.Empty -> {
                                showMsg("空数据")
                            }
                            is HomeSimpleTypeState.Success -> {
                                mAdapter?.setData(it.data)
                            }
                            is HomeSimpleTypeState.Error -> {
                                showMsg("失败"+it.message)
                            }
                            is HomeSimpleTypeState.Success1 -> {}
                            is HomeSimpleTypeState.Success2 -> {}
                        }
                    }
                }
            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                launch {
                    mViewModel.simpleTypeStateFlow2_.collect{
                        when(it){
                            is HomeSimpleTypeState.Init -> {}
                            is HomeSimpleTypeState.Loading -> {}
                            is HomeSimpleTypeState.Empty -> {
                                // 处理空数据情况
                                if (currentPage == 1) {
                                    videoList.clear()
                                    showMsg("空数据")
                                } else {
                                    hasMoreData = false
                                }
                                updateUI()
                            }
                            is HomeSimpleTypeState.Success2 -> {
                                if (currentPage == 1) {
                                    // 刷新数据
                                    videoList.clear()
                                }
                                
                                // 添加新数据
                                videoList.addAll(it.data)
                                
                                // 判断是否还有更多数据
                                hasMoreData = it.data.size == pageSize
                                
                                updateUI()
                            }
                            is HomeSimpleTypeState.Error -> {
                                showMsg("失败"+it.message)
                                // 加载失败时恢复状态
                                if (currentPage > 1) {
                                    currentPage--
                                }
                                updateUI()
                            }
                            is HomeSimpleTypeState.Success -> {}

                            is HomeSimpleTypeState.Success1 -> {
                            }
                        }
                    }
                }
            }
        }


    }
    
    private fun updateUI() {
        // 更新适配器数据
        if (mAdapter1 == null) {
            mAdapter1 = HomeVideoApter(videoList)
            binding.rv2.adapter = mAdapter1
        } else {
            mAdapter1?.notifyDataSetChanged()
        }
        
        // 停止刷新动画
        binding.swipeRefreshLayout.isRefreshing = false
        
        // 重置加载更多状态
        isLoadingMore = false
    }

//    override fun onDetach() {
//        super.onDetach()
//        FpsMonitor.instance.stop()
//    }
}



